#!/bin/bash
set -euo pipefail

MP3_PREFIX="zako_"
MP3_SUFFIX=".mp3"
MIN_NUM=1
MAX_NUM=17
OUTPUT_DIR="."
MASTER_HEADER="audio_assets.h"

check_dependency() {
    if ! command -v "$1" &> /dev/null; then
        echo "❌ 错误：未找到命令 '$1'，请先安装！"
        if [ "$1" = "xxd" ]; then
            echo "   安装命令（Debian/Ubuntu）：sudo apt install xxd"
            echo "   安装命令（CentOS/RHEL）：sudo dnf install vim-common"
        fi
        exit 1
    fi
}

check_dependency "xxd"
check_dependency "sed"  # 确保sed可用

if [ ! -d "$OUTPUT_DIR" ]; then
    echo "📂 创建输出目录：$OUTPUT_DIR"
    mkdir -p "$OUTPUT_DIR"
fi

generate_single_headers() {
    echo -e "\n🚀 开始转换MP3文件为头文件（共 $((MAX_NUM - MIN_NUM + 1)) 个）..."
    
    for ((num=MIN_NUM; num<=MAX_NUM; num++)); do
        mp3_file="${MP3_PREFIX}${num}${MP3_SUFFIX}"
        header_file="${OUTPUT_DIR}/${MP3_PREFIX}${num}_${MP3_SUFFIX:1}.h"
        
        if [ ! -f "$mp3_file" ]; then
            echo "⚠️  警告：未找到文件 $mp3_file，跳过此文件！"
            continue
        fi
        
        if [ -f "$header_file" ]; then
            read -p "❓ 头文件 $header_file 已存在，是否覆盖？(y/N) " -n 1 -r
            echo ""
            if [[ ! $REPLY =~ ^[Yy]$ ]]; then
                echo "⏭️  跳过 $header_file"
                continue
            fi
        fi
        
        echo "🔄 转换 $mp3_file → $header_file"
        xxd -i "$mp3_file" "$header_file"
        
        # 关键修正：给长度变量添加const，使其成为编译时常量
        sed -i 's/unsigned int \([a-zA-Z0-9_]*_len\)/const unsigned int \1/' "$header_file"
    done
    
    echo -e "\n✅ 单个MP3头文件生成完成！"
}

generate_master_header() {
    master_path="${OUTPUT_DIR}/${MASTER_HEADER}"
    
    if [ -f "$master_path" ]; then
        read -p "❓ 整合头文件 $master_path 已存在，是否覆盖？(y/N) " -n 1 -r
        echo ""
        if [[ ! $REPLY =~ ^[Yy]$ ]]; then
            echo "⏭️  跳过 $master_path"
            return
        fi
    fi
    
    echo "🚀 开始生成整合头文件：$master_path"
    
    cat > "$master_path" << EOF
#ifndef AUDIO_ASSETS_H
#define AUDIO_ASSETS_H

/* 自动生成的音频资源整合头文件 */
/* 生成脚本：gen.sh */

EOF

    echo -e "\n/* 包含各音频文件的头文件 */" >> "$master_path"
    for ((num=MIN_NUM; num<=MAX_NUM; num++)); do
        header_file="${MP3_PREFIX}${num}_${MP3_SUFFIX:1}.h"
        if [ -f "${OUTPUT_DIR}/${header_file}" ]; then
            echo "#include \"$header_file\"" >> "$master_path"
        fi
    done

    echo -e "\n/* 音频资源结构体：存储MP3二进制数据和长度 */" >> "$master_path"
    cat >> "$master_path" << EOF
typedef struct {
    const unsigned char* data;  // MP3二进制数据指针
    const unsigned int len;     // 修正：长度也设为const（与头文件对应）
} AudioAsset;

EOF

    echo -e "/* 音频资源列表（共 AUDIO_ASSET_COUNT 个） */" >> "$master_path"
    echo "static const AudioAsset audio_assets[] = {" >> "$master_path"
    
    for ((num=MIN_NUM; num<=MAX_NUM; num++)); do
        header_file="${MP3_PREFIX}${num}_${MP3_SUFFIX:1}.h"
        if [ -f "${OUTPUT_DIR}/${header_file}" ]; then
            data_var="${MP3_PREFIX}${num}_${MP3_SUFFIX:1}"
            len_var="${data_var}_len"
            if [ "$num" -eq "$MAX_NUM" ]; then
                echo "    {${data_var}, ${len_var}}" >> "$master_path"
            else
                echo "    {${data_var}, ${len_var}}," >> "$master_path"
            fi
        fi
    done
    
    echo "};" >> "$master_path"
    echo -e "\n/* 音频资源总数（自动计算） */" >> "$master_path"
    echo "#define AUDIO_ASSET_COUNT (sizeof(audio_assets) / sizeof(AudioAsset))" >> "$master_path"
    echo -e "\n#endif // AUDIO_ASSETS_H" >> "$master_path"
    
    echo "✅ 整合头文件生成完成！"
}

main() {
    echo "========================================"
    echo "      MP3 to C Header Generator        "
    echo "========================================"
    
    generate_single_headers
    generate_master_header
    
    echo -e "\n🎉 所有操作完成！"
    echo -e "📁 生成的文件位于：$OUTPUT_DIR"
}

main
